<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 155px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <label for="">姓名：</label>
            <el-input
                v-model="searchForm.realName"
                placeholder="请输入姓名"
                style="width: 155px"
                clearable
            />
        </div>
        <div class="filter-item">
            <label for="">账号：</label>
            <el-input
                v-model="searchForm.username"
                placeholder="请输入账号"
                style="width: 155px"
                clearable
            />
        </div>
        <div class="filter-item">
            <label for="">手机号：</label>
            <el-input
                v-model="searchForm.phone"
                placeholder="请输入手机号"
                style="width: 155px"
                clearable
            />
        </div>
        <div class="filter-item">
            <label for="">是否启用：</label>
            <el-select
                v-model="searchForm.isDelete"
                class="m-2"
                style="width: 155px"
            >
                <el-option
                    v-for="item in isDeleteList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button
                size="default"
                type="primary"
                @click="search"
            >查询</el-button>
        </div>
        <div class="filter-item">
            <el-button
                type="primary"
                @click="reset"
            >重置</el-button>
        </div>
    </div>

    <div class="filter">
        <div class="filter-item">
            <el-button
                type="primary"
                @click="handleClick('add')"
            >新增</el-button>
        </div>
    </div>
    <el-table
        :data="tableData"
        style="width: 100%"
        border
    >
        <el-table-column
            type="index"
            label="序号"
            width="55"
        />
        <el-table-column
            prop="depId"
            label="所属单位"
        >
            <template #default="scope">
                {{ depNameTranslate(scope.row.depId) }}
            </template>
        </el-table-column>
        <el-table-column
            prop="username"
            label="账号"
        > </el-table-column>
        <el-table-column
            prop="realName"
            label="姓名"
        />
        <el-table-column
            prop="phone"
            label="手机号"
        />
        <el-table-column
            prop="status"
            label="状态"
        >
            <template #default="scope">
                <span :style="{
                        color:
                            scope.row.isDelete == '0' ? '#67c23a' : '#f56c6c',
                    }">{{ scope.row.isDelete == "0" ? "启用" : "禁用" }}</span>
            </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="权责"
        >
            <template #default="scope">
                <el-tag
                    v-for="item in scope.row.roleNames"
                    :key="item"
                    type="primary"
                    style="margin: 2px"
                >
                    {{ item }}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="220"
        >
            <template #default="scope">
                <el-button
                    text
                    type="primary"
                    size="small"
                    @click="handleEdit(scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    @click="handleDetail(scope.row)"
                >
                    详情
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    @click="handleResetPassword(scope.row)"
                >重置密码</el-button>
                <el-button
                    text
                    :type="scope.row.isDelete == '0' ? 'danger' : 'success'"
                    size="small"
                    @click="handleChangeStatus(scope.row)"
                >{{
                        scope.row.isDelete == "0" ? "禁用" : "启用"
                    }}</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog
        v-model="addVisible"
        :title="
            addVisibleType == 'add'
                ? '新增'
                : addVisibleType == 'edit'
                ? '编辑'
                : '详情'
        "
        width="680"
    >
        <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item
                label="所属单位："
                prop="depId"
                required
            >
                <el-select
                    v-model="ruleForm.depId"
                    class="m-2"
                    placeholder="请选择所属单位"
                    style="width: 190px"
                    :disabled="
                        localTypeUnit != '1' || addVisibleType == 'detail'
                    "
                >
                    <el-option
                        v-for="item in newDepIdList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item
                label="账号："
                prop="username"
                required
            >
                <el-input
                    v-model="ruleForm.username"
                    style="width: 190px"
                    :disabled="addVisibleType == 'detail'"
                />
            </el-form-item>
            <el-form-item
                label="姓名："
                prop="realName"
                required
            >
                <el-input
                    v-model="ruleForm.realName"
                    style="width: 190px"
                    :disabled="addVisibleType == 'detail'"
                />
            </el-form-item>
            <el-form-item
                label="手机号："
                prop="phone"
                required
            >
                <el-input
                    v-model="ruleForm.phone"
                    style="width: 190px"
                    :disabled="addVisibleType == 'detail'"
                />
            </el-form-item>

            <el-form-item
                label="权责："
                prop="depId"
                required
            >
                <el-select
                    v-model="ruleForm.roleIds"
                    class="m-2"
                    multiple
                    placeholder="请选择权责"
                    style="width: 190px"
                    :disabled="addVisibleType == 'detail'"
                >
                    <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                        :disabled="item.id == '1' || item.id == '2'"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    v-show="addVisibleType !== 'detail'"
                    @click="submitForm(ruleFormRef)"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="resetPasswordVisible"
        title="重置密码"
        width="400"
    >
        <el-form
            ref="ruleFormRef2"
            :model="ruleForm2"
            :rules="rules2"
            label-width="120"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item
                label="账号："
                prop="username"
            >
                <span>{{ ruleForm2.username }}</span>
            </el-form-item>
            <el-form-item
                label="新密码"
                prop="pass"
                required
            >
                <el-input
                    v-model="ruleForm2.pass"
                    type="password"
                    autocomplete="off"
                />
            </el-form-item>
            <el-form-item
                label="确认密码"
                prop="checkPass"
                required
            >
                <el-input
                    v-model="ruleForm2.checkPass"
                    type="password"
                    autocomplete="off"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="resetPasswordVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="resetPasswordForm(ruleFormRef2)"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import userHttp from "@/https/user.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref, watch } from "vue";

const depIdList = ref([
    { label: "公司", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const newDepIdList = ref([
    { label: "公司", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const isDeleteList = ref([
    { label: "启用", value: "0" },
    { label: "停用", value: "1" },
]);

const depNameTranslate = (depId) => {
    let depName = "";
    newDepIdList.value.forEach((item) => {
        if (item.value == depId) {
            depName = item.label;
        }
    });
    return depName;
};
const searchForm = reactive({
    depId: "",
    phone: "",
    realName: "",
    username: "",
    isDelete: "0",
    pageNo: 1,
    pageSize: 10,
});
const tableData = ref([]);
const addVisible = ref(false);
const addVisibleType = ref(false);
const resetPasswordVisible = ref(false);
const currentUserInfo = ref();
const ruleFormRef = ref();
const ruleFormRef2 = ref();
const ruleForm = reactive({
    depId: "",
    username: "",
    realName: "",
    phone: "",
    isDelete: 0,
    roleIds: [],
    roleNames: [],
    pageNo: 1,
    pageSize: 1000,
});
const ruleForm2 = reactive({
    pass: "",
    checkPass: "",
    username: "",
});
const validatePass = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请输入密码！"));
    } else {
        if (ruleForm2.checkPass !== "") {
            if (!ruleFormRef2.value) return;
            ruleFormRef2.value.validateField("checkPass");
        }
        callback();
    }
};
const validatePass2 = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请再次输入密码"));
    } else if (value !== ruleForm2.pass) {
        callback(new Error("两次密码输入不一致"));
    } else {
        callback();
    }
};
const validatePhone = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请输入手机号码"));
    } else {
        const pattern = /^1[3-9]\d{9}$/;
        let patternFlag = pattern.test(value);
        if (patternFlag) {
            callback();
        } else {
            callback(new Error("请输入正确的手机号码"));
        }
    }
};
const rules2 = reactive({
    pass: [{ validator: validatePass, trigger: "blur" }],
    checkPass: [{ validator: validatePass2, trigger: "blur" }],
});
const rules = reactive({
    depId: [
        {
            required: true,
            message: "请输入所属单位",
            trigger: "blur",
        },
    ],
    username: [
        {
            required: true,
            message: "请输入账号",
            trigger: "blur",
        },
    ],
    realName: [
        {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
        },
    ],
    phone: [
        {
            required: true,
            validator: validatePhone,
            trigger: "blur",
        },
    ],
});

let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value + "";
ruleForm.depId = localTypeUnit.value + "";
const search = async () => {
    const res = await userHttp.userQueryUserList(searchForm);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.depId = item.depId + "";
        });
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
    }
};
watch(
    () => ruleForm.depId,
    () => {
        queryRoleList();
    }
);
const roleList = ref();
const queryRoleList = async () => {
    let params = {
        depId: ruleForm.depId,
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await userHttp.queryRoleList(params);
    if (res.data.code === 200) {
        roleList.value = res.data.data.records;
    }
};
const handleClick = async (type) => {
    ruleForm.depId = localTypeUnit.value + "";
    ruleForm.id = "";
    ruleForm.username = "";
    ruleForm.realName = "";
    ruleForm.phone = "";
    ruleForm.roleIds = [];
    ruleForm.roleNames = [];
    addVisible.value = true;
    addVisibleType.value = type;
};

const reset = () => {
    searchForm.depId = localTypeUnit.value + "";
    searchForm.phone = "";
    searchForm.realName = "";
    searchForm.username = "";
    searchForm.isDelete = "0";
    searchForm.pageNo = 1;
    searchForm.pageSize = 10;
    search();
};
const editDefaultDepId = ref()
const handleEdit = async (row, formEl) => {
    addVisible.value = true;
    addVisibleType.value = "edit";
    editDefaultDepId.value = row.depId;
    ruleForm.depId = row.depId;
    ruleForm.id = row.id;
    ruleForm.username = row.username;
    ruleForm.realName = row.realName;
    ruleForm.phone = row.phone;
    ruleForm.roleIds = row.roleIds;
    ruleForm.roleNames = row.roleNames;
    console.log(ruleForm, "ruleForm");
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (addVisibleType.value == "add") {
                userHttp.userUpdateUser(ruleForm).then((res) => {
                    if (res.data.code == 200) {
                        addVisible.value = false;
                        ElMessage({
                            type: "success",
                            message: "修改成功",
                        });
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            }
        } else {
            ElMessage({
                message: "提交错误",
                type: "error",
            });
        }
    });
};
const handleDetail = (row) => {
    addVisible.value = true;
    addVisibleType.value = "detail";
    ruleForm.id = row.id;
    ruleForm.depId = row.depId;
    ruleForm.username = row.username;
    ruleForm.realName = row.realName;
    ruleForm.phone = row.phone;
    ruleForm.roleIds = row.roleIds;
    ruleForm.roleNames = row.roleNames;
};
const handleResetPassword = (row) => {
    currentUserInfo.value = row;
    resetPasswordVisible.value = true;
    ruleForm2.username = row.username;
};
const handleChangeStatus = (row) => {
    let tipType = row.isDelete == 0 ? "禁用" : "启用";
    ElMessageBox.confirm(
        `确认${tipType}用户【${row.username}】吗？`,
        `${tipType}`,
        {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }
    ).then(() => {
        let params = {
            ...row,
            isDelete: row.isDelete == 0 ? 1 : 0,
        };
        userHttp.userDelUser(params).then((res) => {
            if (res.data.code == 200) {
                ElMessage({
                    type: "success",
                    message: row.isDelete == 0 ? "禁用成功" : "启用成功",
                });
                search();
            }
        });
    });
};
const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (addVisibleType.value == "add") {
                userHttp.userAddUser(ruleForm).then((res) => {
                    if (res.data.code == 200) {
                        addVisible.value = false;
                        ElMessage({
                            message: "新增成功",
                            type: "success",
                        });
                        search();
                    } else {
                        ElMessage({
                            message: res.data.msg,
                            type: "error",
                        });
                    }
                });
            } else {
                if (localTypeUnit.value == "1") {
                    if (editDefaultDepId.value != ruleForm.depId) {
                        ElMessageBox.confirm(
                            `修改所属单位，将清空该账号即日起的排班表、所属班组及所属组织/权责，请确认各项任务已交接`,
                            "注意",
                            {
                                confirmButtonText: "确认",
                                cancelButtonText: "取消",
                                type: "warning",
                            }
                        )
                            .then(() => {
                                userHttp.userUpdateUser(ruleForm).then((res) => {
                                    if (res.data.code == 200) {
                                        addVisible.value = false;
                                        ElMessage({
                                            message: "修改成功",
                                            type: "success",
                                        });
                                        search();
                                    } else {
                                        ElMessage({
                                            message: res.data.msg,
                                            type: "error",
                                        });
                                    }
                                });
                            })
                    } else {
                        userHttp.userUpdateUser(ruleForm).then((res) => {
                            if (res.data.code == 200) {
                                addVisible.value = false;
                                ElMessage({
                                    message: "修改成功",
                                    type: "success",
                                });
                                search();
                            } else {
                                ElMessage({
                                    message: res.data.msg,
                                    type: "error",
                                });
                            }
                        });
                    }
                } else {
                    userHttp.userUpdateUser(ruleForm).then((res) => {
                        if (res.data.code == 200) {
                            addVisible.value = false;
                            ElMessage({
                                message: "修改成功",
                                type: "success",
                            });
                            search();
                        } else {
                            ElMessage({
                                message: res.data.msg,
                                type: "error",
                            });
                        }
                    });
                }
            }
        } else {
            ElMessage({
                message: "提交错误",
                type: "error",
            });
        }
    });
};
const resetPasswordForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let params = {
                ...currentUserInfo.value,
                password: ruleForm2.pass,
            };
            userHttp.userUpdateUser(params).then((res) => {
                if (res.data.code == 200) {
                    resetPasswordVisible.value = false;
                    search();
                } else {
                    ElMessage({
                        message: res.data.msg,
                        type: "error",
                    });
                }
            });
        } else {
            ElMessage({
                message: "修改错误",
                type: "error",
            });
        }
    });
};
onMounted(() => {
    search();
    queryRoleList();
});
</script>

<style scoped lang="less">
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}
.paginationStyle {
    justify-content: flex-end;
    margin-top: 10px;
}
</style>